package com.crois.barrier.transport.heartbeat;

import com.crois.barrier.common.spi.SpiOrder;
import com.crois.barrier.common.utils.OkHttpTools;
import com.crois.barrier.common.utils.SystemUtils;
import com.crois.barrier.common.utils.UtilsAndCommons;
import com.crois.barrier.transport.transport.HeartBeatSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author Hou Ze Yu
 * @description
 * @date 2020/10/23
 */
@SpiOrder(SpiOrder.LOWEST_PRECEDENCE-100)
public class HttpHeartbeatSender implements HeartBeatSender {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpHeartbeatSender.class);

    @Override
    public boolean sendHeartbeat(String serverName,String adminServer, String localAddress, int serverPort) throws Exception {

        LOGGER.debug("【heart beat send】, server:{},开始向管理端心跳发送",adminServer);
        String heartbeatUrl = "http://"+adminServer+ UtilsAndCommons.DEFAULT_BARRIER_ADMIN_HEALTH_BEAT_CHECK_CONTEXT+UtilsAndCommons.BARRIER_HEARTBEAT_CONTEXT;
        String    param = "?ip="+localAddress+"&port="+serverPort+"&lastBeat="+System.currentTimeMillis()+"&healthy=true&enabled=true&load="+
                SystemUtils.getLoad()+"&cpu="+SystemUtils.getCPU()+"&mem="+SystemUtils.getMem()
                +"&serverName="+serverName;
        heartbeatUrl = heartbeatUrl+param;
        try {
            OkHttpTools.getInstance().get(heartbeatUrl);
        } catch (Exception e) {
            LOGGER.error("【heart beat send】, server:{},向管理端心跳发送失败！",adminServer);
        }
        return false;
    }

    @Override
    public long intervalMs() {

        return 5000;
    }
}
